package org.goobs.database;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class ResultFactory {

	private ResultSet results;
	private ResultSetMetaData metaData;
	private Table parent;
	private boolean hasNext;

	protected ResultFactory(ResultSet rs, ResultSetMetaData meta, Table parent) {
		this.results = rs;
		this.metaData = meta;
		this.parent = parent;
		try {
			hasNext = rs.next();
		} catch (SQLException e) {
			hasNext = false;
		}
	}

	public boolean hasMoreRows() {
		return hasNext;
	}

	public boolean fillObject(DatabaseRow row) {
		try {
			Map<String, Object> data = new HashMap<String, Object>();
			int colCount;
			if(metaData != null){
				colCount = metaData.getColumnCount();
				for (int i = 1; i <= colCount; i++) {
					String name = metaData.getColumnName(i);
					Object obj = results.getObject(i);
					data.put(name, obj);
				}
				row.load(data);
				hasNext = results.next();
				return true;
			}else{
				if(parent == null){
					throw new IllegalStateException("Cannot create a sqlite result set without parent table");
				}
				for(String name : parent.getColumns()){
					Object obj = results.getObject(name);
					data.put(name, obj);
				}
				row.load(data);
				hasNext = results.next();
				return true;
			}
		} catch (SQLException e) {
			return false;
		}
	}
}
